package com.zhihu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhihu.client.LikeClient;
import com.zhihu.client.OpnClient;
import com.zhihu.dao.AnswerRepository;
import com.zhihu.dao.AnswerReqDao;
import com.zhihu.pojo.Answer;
import com.zhihu.pojo.User;
import com.zhihu.pojo.baseVo.BaseResult;
import com.zhihu.pojo.req.AnswerReq;
import com.zhihu.service.AnswerService;
import com.zhihu.utils.HeaderUtils;
import com.zhihu.utils.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class AnswerServiceImpl implements AnswerService {

    @Autowired
    AnswerReqDao answerReqDao;

    @Autowired
    HeaderUtils headerUtils;

    @Autowired
    OpnClient opnClient;

    @Autowired
    LikeClient likeClient;

    @Autowired
    AnswerRepository answerRepository;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    //通过问题id查询该问题所有回答,并按点赞数量从高到低排序
    public BaseResult findAnswersByQuestionId(Integer questionId) {
        BaseResult baseResult = new BaseResult();
        List<Answer> list = answerRepository.findByQuestionId(questionId);
        if (!list.isEmpty()) {
            //因为数据库中的点赞数有可能未从redis中更新，所以这里从redis里将查询出的comments点赞字段更新
            for (Answer answer:list) {
                String key = RedisKeyUtils.getLikedOpusCountKey(answer.getOpusTap().toString(),answer.getAnswerId().toString());
                Integer likenums  = (Integer) redisTemplate.opsForHash().get(RedisKeyUtils.MAP_USER_OPUS_COUNT, key);
                answer.setAnsLikenum(likenums);
                //更新字段
                answerRepository.saveAndFlush(answer);
            }
            //所有评论字段更新后，再依照点赞数排序查询封装到集合中
            List<AnswerReq> answersList = answerReqDao.findAnswersByQuestionId(questionId);
            if (!answersList.isEmpty()){
                Long answersCount = answerReqDao.findAnswersCount(questionId);
                System.out.println(answersCount);
                baseResult.setCode(0);
                baseResult.setMsg("查询回答成功！");
                baseResult.setData(answersList);
                baseResult.setCount(answersCount);
                return baseResult;

            }else {
                baseResult.setCode(1);
                baseResult.setMsg("还没有人回答哦！");
                return baseResult;
            }
        }
        baseResult.setCode(1);
        baseResult.setMsg("还没有人回答哦！");
        return baseResult;

    }

    @Override
    //根据问题id添加回答，需要前端传入问题id和问题标题
    public BaseResult addAnswers(AnswerReq answerReq, HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();
        String userJson = headerUtils.getUserJson(request);
        User user = JSONObject.parseObject(userJson, User.class);
        String content = answerReq.getAnsContent();
        StringBuilder builder = new StringBuilder();
        char[] ss = content.toCharArray();

        for (int i =3; i<ss.length-4;i++){
            builder.append(ss[i]);
        }
        System.out.println(builder);
        answerReq.setAnsContent(builder.toString());

        if (user!=null) {
            answerReq.setUserId(user.getUserId());
            answerReq.setAnsCommNums(0);
            answerReq.setAnsCreatetime(new Date());
            answerReq.setAnsLikenum(0);
            answerReq.setAnsUserImg(user.getImg());
            answerReq.setAnsUserName(user.getUserName());
            answerReq.setColumn(0);
            answerReq.setOpusTap(2);
            int i = answerReqDao.addAnswers(answerReq);
            System.out.println(answerReq);
            System.out.println(answerReq.getAnswerId());
            if (i > 0) {
                opnClient.insertKeyToRedis(answerReq.getOpusTap(),answerReq.getAnswerId());
                likeClient.insertOpusLikeNums(answerReq.getOpusTap(),answerReq.getAnswerId());
                baseResult.setCode(0);
                baseResult.setMsg("回答成功！");
                AnswerReq answerByAnswerId = answerReqDao.findAnswerByAnswerId(answerReq.getAnswerId());
                baseResult.setData(answerByAnswerId);
                return baseResult;
            }
            baseResult.setCode(1);
            baseResult.setMsg("回答失败");
            return baseResult;
        }
        baseResult.setCode(2);
        baseResult.setMsg("请先登录！");
        return baseResult;
    }

    @Override
    public BaseResult findAnswerById(Integer answerId) {
        BaseResult baseResult = new BaseResult();
        Answer answer = answerRepository.findByAnswerId(answerId);
        if (answer!=null){
            baseResult.setCode(0);
            baseResult.setMsg("查询成功！");
            baseResult.setData(answer);
            return baseResult;
        }
        baseResult.setCode(1);
        baseResult.setMsg("查询失败！");
        return baseResult;
    }

    @Override
    public BaseResult updateAnswer(Answer answer) {
        BaseResult baseResult = new BaseResult();
        if (answer!=null){
            answerRepository.saveAndFlush(answer);
            baseResult.setCode(0);
            baseResult.setMsg("更新数据成功！");
            return baseResult;
        }
        baseResult.setCode(1);
        baseResult.setMsg("更新数据失败！");
        return baseResult;
    }
}
